#include "Include/IconProvider.h"
#include "CurrentEditor.h"
#include "FindDialog.h"
#include "ui_FindDialog.h"

FindDialog::FindDialog(CurrentEditor * edit, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FindDialog),
    _editor(edit)
{
    ui->setupUi(this);
    ui->closeBtn->setIcon(IconProvider::instance()->icon("window-close"));
    connect(ui->closeBtn, SIGNAL(clicked()), SLOT(hide()));
    emit findAvailable(false);

    connect(ui->findEdt, SIGNAL(textChanged(QString)), SLOT(onTextChanged(QString)));
    connect(ui->findEdt, SIGNAL(returnPressed()), SIGNAL(findNext()));
    connect(ui->findNextBtn, SIGNAL(clicked()), SIGNAL(findNext()));
    connect(ui->findPrevBtn, SIGNAL(clicked()), SIGNAL(findPrevious()));
    connect(ui->replaceBtn, SIGNAL(clicked()), SIGNAL(replace()));
    connect(ui->replaceFindBtn, SIGNAL(clicked()), SIGNAL(replaceFind()));
    connect(ui->replaceAllBtn, SIGNAL(clicked()), SIGNAL(replaceAll()));

    connect(ui->replaceEdt, SIGNAL(textChanged(QString)), SLOT(onReplaceChanged(QString)));
    connect(ui->replaceEdt, SIGNAL(returnPressed()), SIGNAL(replaceFind()));
}

FindDialog::~FindDialog()
{
    delete ui;
}

void FindDialog::showEvent(QShowEvent *)
{
    ui->findEdt->setFocus(Qt::TabFocusReason);
    QString selText = _editor->selectedText();
    if (!selText.isEmpty() && !selText.contains("\n")){
        ui->findEdt->setText(selText);
        ui->findEdt->selectAll();
    }
}

void FindDialog::activate()
{
    ui->findEdt->setFocus(Qt::TabFocusReason);
    ui->findEdt->selectAll();
}

void FindDialog::onTextChanged(const QString& text)
{
    emit findAvailable(!text.isEmpty());
    emit findNext();
}

QString FindDialog::findText()
{
    return ui->findEdt->text();
}

QString FindDialog::replaceText()
{
    return ui->replaceEdt->text();
}

void FindDialog::onReplaceChanged(const QString& text)
{
    emit replaceAvailable(!text.isEmpty());
}
